package com.web.exiaodao.business.controller;
import com.web.exiaodao.business.entity.Category;
import com.web.exiaodao.business.service.CategoryService;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.controller.BaseController;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.jpa.WebUitl;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: ShopCategoryController.java
 * @Package com.web.webstart.business.controller
 * @Description: 分类表控制器  1：商品 ：2：资讯
 * @author eason.zt
 * @date 2016-11-29 12:09:17
 * @version V1.0
 */
@Controller
@RequestMapping("/cms/category")
public class CategoryController extends BaseController {

	private static final Logger LOGGER = Logger.getLogger(CategoryController.class);

	@Autowired
	private CategoryService categoryService;
	
	/**
	 * @Title: findShopCategoryNEStatusPage
	 * @Description: 分页查询ShopCategory	 * @param nextPage
	 * @param pageSize
	 * @param status		//默认查询非删除3的数据,具体类型参照XaConstant.Status
	 * @param sortData
	 * @param jsonFilter
	 * @return    
	 */
	@ResponseBody
	@RequestMapping(value="findShopCategoryNEStatusPage",method=RequestMethod.POST)
	public XaResult<Page<Category>> findShopCategoryNEStatusPage(
		@RequestParam(defaultValue = "0") Integer nextPage,
		@RequestParam(defaultValue = "10") Integer pageSize,
		@RequestParam(defaultValue = "3") Integer status,
		@RequestParam(defaultValue = "[{property:'categoryOrder',direction:'ASC'},{property:'createTime',direction:'DESC'}]") String sortData,
		@RequestParam(defaultValue = "{}") String jsonFilter
	) throws BusinessException{
		Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, sortData);
		Map<String,Object> filterParams =  WebUitl.getParametersStartingWith(jsonFilter, "search_");
		return categoryService.findListNEStatusByFilter(status, filterParams, pageable);
	}
	
	/**
	 * @Title: findShopCategoryEQStatusPage
	 * @Description: (预留)分页查询ShopCategory	 * @param nextPage
	 * @param pageSize
	 * @param status		//默认查询正常状态1的数据,具体类型参照XaConstant.Status
	 * @param sortData
	 * @param jsonFilter
	 * @return    
	 */
	@ResponseBody
	@RequestMapping(value="findShopCategoryEQStatusPage",method=RequestMethod.POST)
	public XaResult<Page<Category>> findShopCategoryEQStatusPage(
		@RequestParam(defaultValue = "0") Integer nextPage,
		@RequestParam(defaultValue = "10") Integer pageSize,
		@RequestParam(defaultValue = "1") Integer status,
		@RequestParam(defaultValue = "[{property:'categoryOrder',direction:'ASC'}]") String sortData,
		@RequestParam(defaultValue = "{}") String jsonFilter
	) throws BusinessException{
		Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, sortData);
		Map<String,Object> filterParams =  WebUitl.getParametersStartingWith(jsonFilter, "search_");
		return categoryService.findListEQStatusByFilter(status, filterParams, pageable);
	}
	
	/**
	 * @Title: findShopCategoryById
	 * @Description: 根据ID查找单条实体
	 * @param modelId
	 * @return    
	 */
	@ResponseBody
	@RequestMapping(value="findShopCategoryById",method=RequestMethod.POST)
	public XaResult<Category> findShopCategoryById(
		@RequestParam Long modelId
	) throws BusinessException{
		return categoryService.findOne(modelId);
	}
	/**
	 * @Title: saveModel
	 * @Description: 保存实体数据
	 * @param model
	 * @return    
	 */
	@ResponseBody
	@RequestMapping(value="saveShopCategory",method=RequestMethod.POST)
	public XaResult<Category> saveShopCategory(
		Category model
	) throws BusinessException{
		XaResult<Category> xr = new XaResult<Category>();
		try{
			return categoryService.saveOrUpdate(model);
		}catch(Exception e){
			LOGGER.error(XaConstant.Message.error,new Throwable(e));
			xr.error(XaConstant.Message.error);
		}
		return xr;
	}
	
	/**
	 * @Title: multiOperateShopCategoryByIds
	 * @Description: 批量操作多个实体状态,根据status进行操作
	 * @param modelIds    	多个实体id,中间用逗号隔开
	 * @param status 		操作类型,status类型见XaConstant.Status,默认删除操作
	 * @return    
	 */
	@ResponseBody
	@RequestMapping(value="operateShopCategoryByIds",method=RequestMethod.POST)
	public XaResult<Category> operateShopCategoryByIds(
		HttpServletRequest request,
		@RequestParam String modelIds,
		@RequestParam(defaultValue = "3") Integer status
	) throws BusinessException{
		return categoryService.multiOperate(modelIds,status);
	}

	/**
	 * @param photoFile
	 * @param request
	 * @return
	 * @Title: upload
	 * @Description: 图片上传
	 */
	@ResponseBody
	@RequestMapping(value = "photoUpload", method = RequestMethod.POST)
	public XaResult<String> photoUpload(
			@RequestParam(value = "photoFile", required = false) MultipartFile photoFile,
			HttpServletRequest request) {
		XaResult<String> xr = new XaResult<String>();
		String root = request.getSession().getServletContext().getRealPath("/");
		String picturePath = "/upload/shopCategory";
		String ext = photoFile.getOriginalFilename().substring(
				photoFile.getOriginalFilename().lastIndexOf("."));
		String newName = new Date().getTime() + ext;
		File filedict = new File(root + picturePath);
		if (!filedict.exists()) {
			filedict.mkdir();
		}
		File targetFile = new File(root + picturePath + File.separator
				+ newName);

		try {
			if (org.apache.commons.lang3.StringUtils.equalsIgnoreCase(ext, ".jpg")
					|| org.apache.commons.lang3.StringUtils.equalsIgnoreCase(ext, ".png")) {
				photoFile.transferTo(targetFile);
				BufferedImage bimg = ImageIO.read(targetFile);
				int width = bimg.getWidth();
				int height = bimg.getHeight();
				Map<String, Integer> map = new HashMap<String, Integer>();
				map.put("pictureHeight", height);
				map.put("pictureWidth", width);
				xr.setCode(1);
				xr.setObject(XaConstant.Code.success + ":" + picturePath + "/"
						+ newName + ":" + height + ":" + width);
			} else {
				xr.setCode(0);
				xr.setObject(XaConstant.Code.error + ":上传文件类型不允许,请上传jpg/png图片");
			}
		} catch (IllegalStateException e) {
			xr.setCode(0);
			xr.setObject(XaConstant.Code.error + ":图片上传失败(Il)");
			return xr;
		} catch (IOException e) {
			xr.setCode(0);
			xr.setObject(XaConstant.Code.error + ":图片上传失败(IO)");
		} catch (Exception e) {
			xr.setCode(0);
			xr.setObject(XaConstant.Code.error + ":图片上传失败(Ex)");
		}
		return xr;
	}
	
}

